package movilmax.sia_corp.action;


import movilmax.sia_corp.model.Listax;

import org.jfree.chart.JFreeChart;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.text.NumberFormat;
import java.util.LinkedList;

import org.jfree.chart.*;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;
import org.jfree.chart.plot.PiePlot3D;

import org.jfree.chart.annotations.CategoryTextAnnotation;
import org.jfree.chart.axis.*;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.*;


import apli.conectar.Conectar;
import basedatos.Resultado;

import com.opensymphony.xwork2.ActionSupport;


public class GrfProspectos  extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private JFreeChart chart;
	private String tipo;


	private LinkedList<Listax> lst_lbs;
	
    private JFreeChart grafica3D(PieDataset piedataset){
    	JFreeChart jfreechart = ChartFactory.createPieChart3D("STATUS PROSPECTOS", piedataset, true, true, false);
        PiePlot3D pieplot = (PiePlot3D)jfreechart.getPlot();
        pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{2}", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));
        pieplot.setStartAngle(290D);
        pieplot.setDirection(Rotation.CLOCKWISE);
        pieplot.setForegroundAlpha(0.5F);
        pieplot.setNoDataMessage("Sin datos para mostrar");
        pieplot.setCircular(true);
        pieplot.setMaximumLabelWidth(0.21D);
        pieplot.setIgnoreNullValues(true);
        pieplot.setIgnoreZeroValues(true);
        pieplot.setBackgroundPaint(Color.white);
        return jfreechart;
    }
    
    private JFreeChart grafica2D(PieDataset piedataset){
        JFreeChart jfreechart = ChartFactory.createPieChart(null, piedataset, true, true, false);
        jfreechart.setBackgroundPaint(new Color(226, 230, 226));
        
        PiePlot pieplot = (PiePlot)jfreechart.getPlot();
        pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{2}", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));
        /*PROPIEDADES DE LA GRAFICA */
        
        jfreechart.setBorderVisible(false);
        
        pieplot.setNoDataMessage("Sin datos para mostrar");
        pieplot.setCircular(true);
        pieplot.setMaximumLabelWidth(0.21D);
        pieplot.setIgnoreNullValues(true);
        pieplot.setIgnoreZeroValues(true);
        pieplot.setBackgroundPaint(new Color(226, 230, 226));
        return jfreechart;
    }
    
    private  PieDataset llenarDatosStx(){
        DefaultPieDataset data = new DefaultPieDataset();
        Conectar BASE=new Conectar();
        String SQL="",crit="";
	     if (BASE.getMsg().equals("SI") ){
	         if( this.getTipo()==null ){
	        	 SQL="select count(P.status) as valor,P.status as des "+
					"from prospectos P "+
					"where P.tipo in('CORPORATIVO','PYME') "+
					"group by p.status "; 
	         }else{
	        	 if(this.getTipo().trim().equals("TODOS") )
	        		 crit=" P.tipo in('CORPORATIVO','PYME')  ";
	        	  else
	        		 crit=" P.tipo ='"+  this.getTipo().trim() +"' "; 
	        	 
	        	 SQL="select count(P.status) as valor,P.status as des "+
					"from prospectos P where "+crit+" group by p.status ";
	         }
	        	 
			Resultado RCS = BASE.getBaseDatos().consultar(SQL);
		    if(RCS.RP){
		    	do{
		    	    data.setValue(RCS.getCadena("des")+" ( "+RCS.getInt("valor") +" )", RCS.getDoble("valor"));
		    	}while(RCS.sigItem());
		    }else{
		    	data.setValue("NINGUNO",0D);
		    }
       }
        return data;
    }
    private CategoryDataset llenarDatosPrg(){
        DefaultCategoryDataset data = new DefaultCategoryDataset();
        Conectar BASE=new Conectar();
        String SQL="",crit="";
	     if (BASE.getMsg().equals("SI") ){
	         if( this.getTipo()==null ){ 
	              SQL="select count(X.descripcion) as valor,X.cod, X.descripcion as des "+
		              "from corp_seguimiento_actividades A,corp_detalles_actividad X "+
		              "where  A.cod in ( select MAX(A.cod) nact "+
		              "from corp_detalles_actividad X,corp_seguimiento_actividades A,prospectos P "+
		              "where X.horas>0 and X.cod=A.detalle and A.prospecto=P.codigo and P.tipo in('CORPORATIVO','PYME') "+
		              "group by P.codigo ) and A.detalle=X.cod "+
		              "group by X.descripcion,X.cod order by X.cod ";
	         }else{
	        	 if(this.getTipo().trim().equals("TODOS") )
	        		 crit=" P.tipo in('CORPORATIVO','PYME')  ";
	        	  else
	        		 crit="  P.tipo ='"+  this.getTipo().trim() +"' "; 
	        	 
	        	 SQL="select count(X.descripcion) as valor,X.cod, X.descripcion as des "+
	              "from corp_seguimiento_actividades A,corp_detalles_actividad X "+
	              "where  A.cod in ( select MAX(A.cod) nact "+
	              "from corp_detalles_actividad X,corp_seguimiento_actividades A,prospectos P "+
	              "where X.horas>0 and X.cod=A.detalle and A.prospecto=P.codigo and "+crit+" "+
	              "group by P.codigo ) and A.detalle=X.cod "+
	              "group by X.descripcion,X.cod order by X.cod ";
	        	 
	         }
	        	 
			Resultado RCS = BASE.getBaseDatos().consultar(SQL);
			int i=1;
			lst_lbs=new LinkedList<Listax>();
		    if(RCS.RP){
		    	do{
		    		Listax VX=new Listax();
		    		VX.setCod("P"+i);
		    		VX.setDescripcion( (RCS.getLong("cod")+2 )+". "+RCS.getCadena("des") );
		    		lst_lbs.add(VX);
		    	    data.addValue(RCS.getDoble("valor"), "PX","P"+i);
		    	    i++;
		    	}while(RCS.sigItem());
		    }else{
		    	data.setValue(0D,"PX","NINGUNO");
		    }
       }
        return data;
    }
    
   @SuppressWarnings("deprecation")
 private JFreeChart graficaPrg(CategoryDataset categorydataset){
        JFreeChart jfreechart = ChartFactory.createBarChart(null, null, null, categorydataset, PlotOrientation.HORIZONTAL, false, true, false);
        
        jfreechart.setBackgroundPaint(Color.white);
        /*TextTitle texttitle = new TextTitle("PROGRESO PROSPECTOS");
        texttitle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        texttitle.setBackgroundPaint(new Color(226, 230, 226));
        texttitle.setPaint(new Color(13, 137, 220));
        jfreechart.setTitle(texttitle);
        */
        CategoryPlot categoryplot = (CategoryPlot)jfreechart.getPlot();
        categoryplot.setOutlinePaint(null);
        categoryplot.setBackgroundPaint(new Color(226, 230, 226));
        categoryplot.setDomainGridlinesVisible(true);
        categoryplot.setDomainGridlinePosition(CategoryAnchor.END);
        categoryplot.setDomainGridlineStroke(new BasicStroke(0.5F));
        categoryplot.setDomainGridlinePaint(Color.black);
        categoryplot.setRangeGridlinesVisible(false);
        categoryplot.clearRangeMarkers();
        CategoryAxis categoryaxis = categoryplot.getDomainAxis();
        categoryaxis.setVisible(false);
        
        categoryaxis.setCategoryMargin(0.5D);
        categoryplot.getRangeAxis().setVisible(false);
        BarRenderer barrenderer = (BarRenderer)categoryplot.getRenderer();
        barrenderer.setSeriesPaint(0, new Color(13, 137, 220));
        
        barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        barrenderer.setOutlineStroke(null);
        barrenderer.setDrawBarOutline(false);
        barrenderer.setItemLabelsVisible(true);
        barrenderer.setItemLabelFont(new Font("Verdana", 1, 7));
        ItemLabelPosition itemlabelposition = new ItemLabelPosition(ItemLabelAnchor.INSIDE3 , TextAnchor.CENTER_RIGHT);
        barrenderer.setPositiveItemLabelPosition(itemlabelposition);
        for(int i=0; i<lst_lbs.size();i++){
        	Listax VX=lst_lbs.get(i);
        	CategoryTextAnnotation categorytextannotation = new CategoryTextAnnotation(VX.getDescripcion(),VX.getCod(), 0.0D);
            categorytextannotation.setFont(new Font("Verdana", 1, 9));
            categorytextannotation.setTextAnchor(TextAnchor.BOTTOM_LEFT);
            categorytextannotation.setCategoryAnchor(CategoryAnchor.START);
            categoryplot.addAnnotation(categorytextannotation);
        }
        return jfreechart;
    }

    
    
    
    public String grf_status() throws Exception {
    	PieDataset datos = llenarDatosStx();
	    chart= grafica2D(datos);
		chart.setBackgroundPaint(java.awt.Color.white);
		return SUCCESS;
	}
    public String grf_status3D() throws Exception {
    	PieDataset datos = llenarDatosStx();
	    chart= grafica3D(datos);
		chart.setBackgroundPaint(java.awt.Color.white);
		return SUCCESS;
	}
    
    public String grf_progreso() throws Exception {
    	chart= graficaPrg(llenarDatosPrg() );
		chart.setBackgroundPaint(java.awt.Color.white);
		return SUCCESS;
	}
    
	public JFreeChart getChart() {
		return chart;
	}

	public String getTipo() {
		return tipo;
	}
	public void setTipo(String tipo) {
		this.tipo = tipo;
	}
	
}
